package cz.muni.fi.pa165.ddtroops.daoclasses;

import cz.muni.fi.pa165.ddtroops.daointerfaces.SquadDAO;
import cz.muni.fi.pa165.ddtroops.entities.Hero;
import cz.muni.fi.pa165.ddtroops.entities.Squad;
import javax.persistence.NoResultException;
import org.springframework.stereotype.Repository;

/**
 * Class SquadDAOImpl serves as a Data Access Object class for entity Squad.
 * SquadDAOImpl class extends generic abstract class BaseDAOImpl. See SquadDAO
 * for set of supported methods.
 *
 * @author Matěj Škrabánek
 */
@Repository(value = "squadDAO")
public class SquadDAOImpl extends BaseDAOImpl<Squad> implements SquadDAO{

    @Override
    protected boolean isValid(Squad object)
    {
        return (object.getGold() != null) && (object.getLeader() != null) &&
               (object.getMembers().contains(object.getLeader())) &&
               (object.getName() != null && !object.getName().isEmpty()) &&
               (object.getTask() != null);
    }

    @Override
    protected boolean isIn(Squad object) {
        return getById(object.getId()) != null;
    }

    public Squad getSquadOfHero(Hero hero) {
        Squad s;
        try{
        s = getEntityManager().createQuery("SELECT s From Squad s INNER JOIN s.members mem WHERE mem.id=:heroId", Squad.class).setParameter("heroId",hero.getId()).getSingleResult();
        }catch(NoResultException ex){
            s = null;
        }
        return s;
    }
}
